<template>
  <view class="register">
    <u-form :model="user" label-width='auto' ref='uForm'>
      <u-form-item required label="用户名" prop='username'>
        <u-input v-model="user.username"></u-input>
      </u-form-item>
      <u-form-item required label="密码" prop='password'>
        <u-input v-model="user.password" type="password"></u-input>
      </u-form-item>
      <u-form-item required label="确认密码" prop='re_password'>
        <u-input v-model="user.re_password" type="password"></u-input>
      </u-form-item>
      <u-form-item class="option">
        <u-button @click="toRegister" type="primary" size="medium">注册</u-button>
        <text class="toLogin" @click="toLogin">去登录</text>
      </u-form-item>
    </u-form>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
  
  import { register } from './_api/index.js'
  export default {
    data () {
      return {
        user: {
          username: null,
          password: null,
          re_password: null,
        },
        errorType: ['message', 'toast'],
        rules: {
          username: [
            {
              required: true,
              message: '请输入用户名',
              trigger: ['blur', 'change']
            }
          ],
          password: [
            {
              min: 6,
              max: 18,
              required: true,
              message: '请输入6-18位密码',
              trigger: 'blur, change'
            }
          ],
          re_password: [
            {
              min: 6,
              max: 18,
              required: true,
              message: '请确认密码',
              trigger: 'blur, change'
            },
            {
              validator: (rule, value, callback) => {
                return this.user.password === this.user.re_password
              },
              message: '两次密码不一样！',
              trigger: 'blur, change'
            }
          ]
        }
      }
    },
    methods: {
      toRegister() {
        this.$refs.uForm.validate(valid => {
          if (valid) {
            register(this.user)
              .then(res => {
                this.$refs.uToast.show({
                  title: '注册成功，正在跳转到登录页',
                  type: 'success',
                  url: '/pages/login/login'
                })
                
              })
              .catch(_ => {})
          } else {
            this.$refs.uToast.show({
              title: '请检查输入项',
              type: 'warning'
            })
          }
        })
      },
      
      toLogin() {
        uni.navigateTo({
          url: '/pages/login/login'
        })
      }
    },
    onReady() {
      this.$refs.uForm.setRules(this.rules);
    }
  }
</script>

<style lang="scss" scoped>
  .register {
    margin: 30rpx auto;
    width: 690rpx;
  }
  .toLogin {
    margin-left: 50rpx;
    cursor: pointer;
    color: blue;
  }
  .option {
    display: flex;
    justify-content: center;
  }
</style>
